package com.xoa.service.file.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.file.FileSortMapper;
import com.xoa.model.department.Department;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.file.FileSortModel;
import com.xoa.model.users.Users;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.service.enclosure.impl.EnclosureServiceImplDemo;
import com.xoa.util.*;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.netdisk.ZipUtils;
import com.xoa.util.treeUtil.CheckTree;

import com.xoa.util.treeUtil.FileCommSortTreeUtil;
import com.xoa.util.treeUtil.TreeNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.xoa.dao.file.FileContentMapper;
import com.xoa.model.file.FileContentModel;
import com.xoa.service.file.FileContentService;
import com.xoa.service.file.FileSortService;
import com.xoa.service.users.UsersService;

import org.springframework.web.multipart.MultipartFile;

@Service
public class FileContentServiceImpl implements FileContentService{
	@Resource
	private	FileContentMapper file_ContentMapper;
	@Resource
	private	FileSortMapper fileSortMapper;
	@Resource
	private	EnclosureServiceImplDemo demo;
	@Resource
	private EnclosureService enclosureService;
	@Resource
	private	FileSortService fileSortService;
	@Resource
	private DepartmentMapper departmentMapper;
	@Resource
	private	UsersService usersService;
	public int deleteBySortId(int sort_id) {
		return file_ContentMapper.deleteBySort_id(sort_id);
	}
	
	
	public List<FileContentModel> getFileConBySortid(int tempNo,HttpServletRequest request) {
	    int sortType= Integer.parseInt(String.valueOf(request.getAttribute("sortType")==null?"0":request.getAttribute("sortType")));
		int sortMode= Integer.parseInt(String.valueOf(request.getAttribute("sortMode")==null?"0":request.getAttribute("sortMode")));
	     
	     
	     Map<String,Object> mapValue=new HashMap<String, Object>();
	     mapValue.put("tempNo",tempNo);
	     
	     String sortSqlString=null;
	     if(sortType==1){
	    	 if(sortMode==1){
	    		 sortSqlString=" order by SEND_TIME  desc";
	    	 }else if(sortMode==2){
	    		 sortSqlString=" order by SEND_TIME  asc";
	    	 }else{
	    		 sortSqlString="order by CONTENT_NO asc";
	    	 }
	     }else if(sortType==2){
             if(sortMode==1){
            	 sortSqlString=" order by CONTENT_NO  desc";
	    	 }else if(sortMode==2){
	    		 sortSqlString=" order by CONTENT_NO asc";
	    	 }else{
	    		 sortSqlString="order by CONTENT_NO asc";
	    	 }
	     }else{
	    	 sortSqlString="order by CONTENT_NO asc";
	     }
	    String userId=request.getSession().getAttribute("userId").toString();
		mapValue.put("sortSqlString", sortSqlString);
		mapValue.put("userId", userId);
		List<FileContentModel>  FileContentList=file_ContentMapper.getFileConBySortid(mapValue);
		for(FileContentModel  fcm:FileContentList){
			String temp=fcm.getSendTime().substring(0, 19);
			fcm.setSendTime(temp);
			fcm.setReaders(readerFlag(userId,fcm.getReaders()));
		}
		return FileContentList;
	}

	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-5-3 下午2:54:56
	 * 方法介绍:   判断已读未读
	 * 参数说明:   @param userId
	 * 参数说明:   @param readers
	 * 参数说明:   @return
	 * @return     String 返回字符串“1”为已读 “0”为未读通过前端判断进行辨别
	 */
	   public static String readerFlag(String userId,String readers){
		   if(readers!=null&&!"".equals(readers)){
	    	 String[] readersStrings=readers.split(",");
			 List<String> userList = Arrays.asList(readersStrings);
			 if(userList.contains(userId)){
				 return "1";
			 }else{
				 return "0";
			 }
		   }
			return "0";
	     }
	   /**
		 * 
		 * 创建作者:   杨 胜
		 * 创建日期:   2017-5-3 下午2:54:56
		 * 方法介绍:   详情
		 * 参数说明:   @param contentId
		 * 参数说明:   @param readers
		 * 参数说明:   @return
		 */
	@Override
	public FileContentModel getFileConByContentId(String contentId,HttpServletRequest request) {
		FileContentModel fc=file_ContentMapper.getFileConByContentId(contentId);
		String temp="";
		if(fc.getSendTime()!=null){
			temp=fc.getSendTime().substring(0, 19);
		}
		fc.setSendTime(temp);
		String userID=request.getSession().getAttribute("userId").toString();
		if("0".equals(readerFlag(userID,fc.getReaders()))){
			FileContentModel fcm=new FileContentModel();
			fcm.setContentId(fc.getContentId());
			if(fc.getReaders()!=null){
				fcm.setReaders(fc.getReaders()+userID+",");
			}else{
				fcm.setReaders(userID+",");
			}
			file_ContentMapper.updateFileCon(fcm);
			}
		return	fc;
	}

	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-5-3 下午2:54:56
	 * 方法介绍:   保存一条文件信息
	 * 参数说明:   @param contentId
	 * 参数说明:   @param readers
	 * 参数说明:   @return
	 */
	public int saveContent(FileContentModel fileContentModel) {
		return file_ContentMapper.saveContent(fileContentModel);
	}

	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-5-3 下午2:54:56
	 * 方法介绍:   删除一条文件信息
	 * 参数说明:   @param contentId
	 * 参数说明:   @param readers
	 * 参数说明:   @return
	 */
	@Override
	public int deleteByConId(Map<String, Object> fileConMap) {
		
		return file_ContentMapper.deleteByConId(fileConMap);
	}

	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-5-3 下午2:54:56
	 * 方法介绍:   修改一条文件信息
	 * 参数说明:   @param contentId
	 * 参数说明:   @param readers
	 * 参数说明:   @return
	 */
	public int updateFileCon(FileContentModel fcm) {
		//System.out.println("--"+fcm.getContent());
		return file_ContentMapper.updateFileCon(fcm);
	}

	public BaseWrapper batchDeleteConId(Integer[] conId) {
		BaseWrapper wrapper =new BaseWrapper();
		if(conId==null||conId.length<1){
			wrapper.setMsg("无效的请求参数");
			wrapper.setStatus(true);
			wrapper.setFlag(false);
			return wrapper;
		}
		int res = file_ContentMapper.batchDeleteConId(conId);
    if(res>0){
		wrapper.setMsg("请求成功");
		wrapper.setStatus(true);
		wrapper.setFlag(true);

	}else{
		wrapper.setMsg("操作失败");
		wrapper.setStatus(true);
		wrapper.setFlag(false);
	}
		return wrapper;
	}

	@Override
	public BaseWrappers queryBySearchValue(HttpServletRequest req,Integer sortId,Integer sortType, String subjectName, String[] creater, Integer contentNo, String contentValue1, String contentValue2, String contentValue3, String atiachmentDesc, String atiachmentName, String atiachmentCont, String crStartDate, String crEndDate,Integer pageNo,Integer pageSize) {
		BaseWrappers wrappers =new BaseWrappers();
		wrappers.setFlag(false);
		wrappers.setStatus(true);
		List<FileContentModel> datas=new ArrayList<FileContentModel>();
		if(pageNo==null){
			pageNo=0;
		}
		StringBuffer createrArray=null;
		String createrArrayStr=null;
		if(creater!=null&&creater.length>0){
			createrArray =new StringBuffer();
			for(String value:creater){
				createrArray.append(value);
				createrArray.append(",");
			}
			createrArrayStr=createrArray.toString();
		}
		if(StringUtils.checkNull(subjectName)){
			subjectName=null;
		}
		if(StringUtils.checkNull(contentValue1)){
			contentValue1=null;
		}
		if(StringUtils.checkNull(contentValue2)){
			contentValue2=null;
		}
		if(StringUtils.checkNull(contentValue3)){
			contentValue3=null;
		}
		if(StringUtils.checkNull(atiachmentDesc)){
			atiachmentDesc=null;
		}if(StringUtils.checkNull(atiachmentName)){
			atiachmentName=null;
		}if(StringUtils.checkNull(atiachmentCont)){
			atiachmentCont=null;
		}
		if(StringUtils.checkNull(crStartDate)){
			crStartDate=null;
		}
		if(StringUtils.checkNull(crEndDate)){
			crEndDate=null;
		}
		if(sortId==0&&sortType==4){
			 datas =file_ContentMapper.rootqueryBySearchValue(sortId,subjectName,createrArrayStr,contentNo,contentValue1,contentValue2,contentValue3,atiachmentDesc,atiachmentName,atiachmentCont,crStartDate,crEndDate,pageNo,pageSize);
		}else{
			datas =file_ContentMapper.queryBySearchValue(sortId,sortType,subjectName,createrArrayStr,contentNo,contentValue1,contentValue2,contentValue3,atiachmentDesc,atiachmentName,atiachmentCont,crStartDate,crEndDate,pageNo,pageSize);
		}
		for(FileContentModel fc:datas){
			List<Attachment> attachmentList=new ArrayList<Attachment>();
			if(fc.getAttachmentName()!=null&&!"".equals(fc.getAttachmentName())){
				attachmentList=GetAttachmentListUtil.returnAttachment(fc.getAttachmentName(),fc.getAttachmentId(),"xoa" + (String) req.getSession().getAttribute("loginDateSouse"),GetAttachmentListUtil.MODULE_FILE_FOLDER);
				}
			fc.setSendTime(fc.getSendTime().substring(0, 19));
			fc.setAttachmentList(attachmentList);
		}
		if(datas.size()>0){
			wrappers.setDatas(datas);
			wrappers.setFlag(true);
			wrappers.setMsg("获取数据成功");
		}else{
			wrappers.setFlag(false);
			wrappers.setMsg("查询无结果");
		}
		return wrappers;
	}

	@Override
	public BaseWrapper copyAndParse(Integer copyId, Integer witchSortId) {
		BaseWrapper wrapper =new BaseWrapper();
		wrapper.setFlag(false);
		wrapper.setStatus(true);
		wrapper.setMsg("操作失败");
//		file_ContentMapper
		//查询所属文件
		if(copyId==null){
			return wrapper;
		}
	   FileContentModel fileContentModel =	file_ContentMapper.selectFileById(copyId);
       if(fileContentModel!=null){
		   //移动当前文件
		   if(witchSortId==null){
			   wrapper.setMsg("无效的复制路径");
			   return wrapper;
		   }
		   //判断路径是否存在
		   if(witchSortId!=0){
		   FileSortModel sortModel = fileSortMapper.getNowFileSortAuth(witchSortId);
		   if(sortModel==null){
			   wrapper.setMsg("无效的复制路径");
			   return wrapper;
		     }
		   }


		   fileContentModel.setSortId(witchSortId);
		   fileContentModel.setContentId(null);
		   int  res = file_ContentMapper.saveContent(fileContentModel);
		   if(res>0){
			   wrapper.setFlag(true);
			   wrapper.setStatus(true);
			   wrapper.setMsg("操作成功");
		   }else{
			   wrapper.setFlag(false);
			   wrapper.setStatus(true);
			   wrapper.setMsg("操作失败");
		   }
	   }else{
       	return wrapper;
	   }

		return wrapper;
	}
	
	
	@Override
	public ToJson contentCut(HttpServletRequest req,String[] contentId) {
		ToJson tojson=new ToJson();
		String  sortId=(String) req.getParameter("sortId");
		//String[]  contentId=(String[])req.getParameterValues("contentId");
		if(contentId.length==0||sortId==null||"".equals(sortId)){
			tojson.setFlag(1);
			tojson.setMsg("参数错误");
			return tojson;
		}
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("sortId", sortId);
		map.put("contentId", contentId);
		int result=file_ContentMapper.contentCut(sortId,contentId);
		if(result==contentId.length){
			tojson.setFlag(0);
			tojson.setMsg("修改成功");
		}else{
			tojson.setFlag(1);
			tojson.setMsg("修改失败");
		}
		return tojson;
	}
	
	
	@Override
	public BaseWrappers uploadFile(MultipartFile[] files, HttpServletRequest request) {
		BaseWrappers baseWrappers = new BaseWrappers();
		baseWrappers.setFlag(false);
		baseWrappers.setMsg("操作失败");
		int a =0;
		try{
			String company=(String) request.getSession().getAttribute(
					"loginDateSouse");
			if(company!=null){
				company="xoa" +company;
			}else{
				company="xoa1001";
			}
			Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
			Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
			if(users!=null&&users.getUserId()!=null){
				List<Attachment> list=enclosureService.upload(files, company, GetAttachmentListUtil.MODULE_FILE_FOLDER);
				if(list!=null&&list.size()>0){
					for(Attachment attachment:list){
						FileContentModel fileContentModel =new FileContentModel();
						Integer sort=Integer.parseInt(request.getParameter("sortId"));
						if(sort!=0){
							FileSortModel file1=new FileSortModel();
						file1.setSortId(sort);
						FileSortModel fileSortModel= fileSortService.getFileSortBySortIds(file1);
						if ("5".equals(fileSortModel.getSortType())){
							double filerSize = 0;
							if (!StringUtils.checkNull(attachment.getFileSize())) {
								if (attachment.getFileSize().indexOf("MB") != -1) {
									String file = attachment.getFileSize().replace("MB", "");
									double size = Double.valueOf(file);
									filerSize += size;
								} else if (attachment.getFileSize().indexOf("KB") != -1) {
									String file = attachment.getFileSize().replace("KB", "");
									double size = Double.valueOf(file);
									double sizeFile = ZipUtils.getM(size);
									BigDecimal b = new BigDecimal(sizeFile);
									double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
									filerSize += f1;
								} else if (attachment.getFileSize().indexOf("B") != -1) {
									String file = attachment.getFileSize().replace("B", "");
									double size = Double.valueOf(file);
									double sizeFile = ZipUtils.getKB(size);
									double sizeFile1 = ZipUtils.getM(sizeFile);
									BigDecimal b = new BigDecimal(sizeFile1);
									double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
									filerSize += f1;
								}
							}

							if (sort!= 0) {
								StringBuffer stringBuffer=new StringBuffer();
								FileSortModel file=new FileSortModel();
								file.setSortId(sort);
								List<FileSortModel>   FileSortModels  =  getfilesDeleteList(file);

								FileSortModels.add(fileSortModel);
								//List<TreeNode> trr = treeFile(sort, request.getSession());
								for(FileSortModel treeNode:FileSortModels){
									stringBuffer.append(treeNode.getSortId());
									if(FileSortModels.size()>1){
										stringBuffer.append(",");
									}

								}
								List<FileContentModel> fileContentModels=new ArrayList<FileContentModel>();
								String sortId="";
								if(!StringUtils.checkNull(stringBuffer.toString())){
									if(FileSortModels.size()>1) {
										sortId = stringBuffer.substring(0, stringBuffer.length() - 1);
									}else {
										sortId=stringBuffer.toString();
									}
									fileContentModels = selectFileSortList(sortId);
								}
								double fileListSize=0;
								for(int i=0;i<fileContentModels.size();i++){
									fileListSize+=Double.parseDouble(fileContentModels.get(i).getFileSize());
								}
								BaseWrapper bassWrapper = fileSortService.getFileAuthBySortId(sort, request);//不想在写个sql了 用个已有的
								if(bassWrapper!=null){
									if( bassWrapper.getData()!=null&&bassWrapper.getData() instanceof FileSortModel){
										FileSortModel model  =(FileSortModel) bassWrapper.getData();
										if(StringUtils.checkNull(String.valueOf(model.getSpaceLimit()))){
										}else {
											double size=Double.valueOf(model.getSpaceLimit());
											if(fileListSize+filerSize<size||size==0.0){

											}else {
												baseWrappers.setStatus(true);
												baseWrappers.setFlag(false);
												baseWrappers.setMsg("文件已经到最大容量");
												return  baseWrappers;
											}
										}
									}
								}

							}
							fileContentModel.setFileSize(String.valueOf(filerSize));
						}
						}

						String subjectName=attachment.getAttachName();

						fileContentModel.setAttachmentId(attachment.getAid()+"@"+attachment.getYm()+"_"+attachment.getAttachId()+",");
						fileContentModel.setSortId(Integer.parseInt(request.getParameter("sortId")));
						fileContentModel.setAttachmentName(subjectName+"*");
						fileContentModel.setSubject(subjectName.substring(0, subjectName.lastIndexOf(".")));
						fileContentModel.setContentNo("0");
						fileContentModel.setCreater(users.getUserId());
						fileContentModel.setSendTime(DateFormat.getCurrentTime());

						a +=file_ContentMapper.saveContent(fileContentModel);
						if(a>0){
							baseWrappers.setStatus(true);
							baseWrappers.setFlag(true);
							baseWrappers.setMsg("上传成功");
						}else{
							baseWrappers.setStatus(true);
							baseWrappers.setFlag(true);
							baseWrappers.setMsg("上传成功，保存失败");
						}
					}

				}else{
					baseWrappers.setStatus(false);
					baseWrappers.setMsg("上传失败");
					return baseWrappers;
				}
			}else{
				return baseWrappers;
			}

		}catch (Exception e){
			e.printStackTrace();
			baseWrappers.setStatus(false);
			baseWrappers.setMsg("文件异常");
			return baseWrappers;
		}

		return baseWrappers;
	}

     //   作者：  刘佩峰
	 //   时间：  2017 - 06 - 15
	 //   接口功能： 新建附件
	@Override
	public BaseWrapper newFileInBox(String fileType,String path) {

		BaseWrapper wrapper =new BaseWrapper();
		String fileName = UUID.randomUUID().toString();
		try{
			File file =new File(path+"/"+fileName+"."+fileType);
			if(!file.exists())
		    {
				file.createNewFile();
			}
			//1.单文件上传
			Attachment rets  = demo.upload(file,"xoa1001",GetAttachmentListUtil.MODULE_MODEL);

            //2.回显用户  返回的数据
            wrapper.setData(rets);
            wrapper.setStatus(true);
            wrapper.setFlag(true);

		}catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return wrapper;
	}
     
	
	/**
	 * 打包文件下载功能
	 */
	public ToJson<?> downFileContent(HttpServletRequest request,HttpServletResponse response,String[] cIds) {
		ToJson<?> tojson=new ToJson();
		String sortName=request.getParameter("sortName");
		 if("".equals(sortName)||sortName==null){
			 sortName="null";
		 } 
		//String[] cIds=request.getParameterValues("contentId");
		//D:\computerDev\apache-tomcat-7.0.76\webapps\xoa\
		String company="xoa" + (String) request.getSession().getAttribute("loginDateSouse");
		String  reqPath=request.getRealPath("/");
		String  basePath=reqPath+"tempFile"+File.separator;
		String  allPath=reqPath+"tempFile"+File.separator+sortName+File.separator;
		for(int i=0;i<cIds.length;i++){
			//获取文件信息
			FileContentModel fileContentModel=file_ContentMapper.getFileConByContentId(cIds[i]);
		    //文件路径
			String  contentPath=allPath+fileContentModel.getSubject()+File.separator+fileContentModel.getSubject()+".html";
			//文件附件路径
			String  attPath=allPath+fileContentModel.getSubject()+File.separator+"附件"+File.separator;
			this.createDir(contentPath);
			this.createDir(attPath);
		     //拼接文件内容
			StringBuilder cententString=new StringBuilder("<html><head><title>");
			cententString.append(fileContentModel.getSubject());
			cententString.append("</title></head><style>body{font-size:12px;} table{border:1px #000 solid;border-collapse:collapse;} table td{border:1px #000 solid;}</style><body><table width='70%' align='center'><tr><td align='center' colspan='2'><b><span class='big'>");
			cententString.append(fileContentModel.getSubject());
			cententString.append("&nbsp;</span></b></td></tr><tr><td height='250' valign='top' colspan='2'>");
			cententString.append(fileContentModel.getContent());
			cententString.append("&nbsp;</td></tr><tr class=small><td width='100'>创建人：</td><td width='400'>");
			cententString.append(fileContentModel.getCreater());
			cententString.append("&nbsp;</td></tr></table></body></html>");
			this.writeContent(cententString,contentPath);
			//获取附件路径
			if(fileContentModel.getAttachmentId()!=null&&!"".equals(fileContentModel.getAttachmentId())){
			//多个附件获取信息
            String[]	ids=fileContentModel.getAttachmentId().split(",");
			for(int a=0;a<ids.length;a++){
				Attachment  att=null;
				StringBuilder sysPath=this.getPath();
				try {
					att=enclosureService.findByAttachId(Integer.parseInt(ids[a].split("@")[0]));
					sysPath.append(this.getLessPath(att,company));
				} catch (Exception e) {
					 e.printStackTrace();
					 tojson.setFlag(1);
					 tojson.setMsg("文件\""+fileContentModel.getSubject()+"\"获取附件信息失败！");
					 File filefolder=new File(basePath+File.separator+sortName+File.separator);
					 this.deleteFile(filefolder);
					 return tojson;
				}
			
			//将附件信息拷贝到指定的目录下 
			boolean flag=this.copy(sysPath.toString(), attPath);
			//拷贝不成功
			 if(!flag){
				 tojson.setFlag(1);
				 tojson.setMsg("文件\""+fileContentModel.getSubject()+"\"附件以损坏！");
				 File filefolder=new File(basePath+File.separator+sortName+File.separator);
				 this.deleteFile(filefolder);
				 return tojson;
			     }
			  }
			}
		}
		try {
			this.doZip(allPath,basePath+File.separator+sortName+".zip");
			 tojson.setFlag(1);
			 tojson.setMsg("文件压缩成功 但未下载成功");
			 Boolean flag=this.down(basePath+File.separator+sortName+".zip",response,sortName+".zip");
			 if(flag){
				 tojson.setFlag(0);
				 tojson.setMsg("文件压缩成功 下载成功");
				 File filefolder=new File(basePath+File.separator+sortName+File.separator);
				 this.deleteFile(filefolder);
				 File file=new File(basePath+File.separator+sortName+".zip");
				 this.deleteFile(file);
			 }
			 return tojson;
		 } catch (UnsupportedEncodingException e) {
		 	 e.printStackTrace();
			 L.a("文件下载编码错误！");
			 tojson.setFlag(1);
			 tojson.setMsg("文件下载编码错误！");
			 return tojson;
		  }catch (IOException e) {
		 	 e.printStackTrace();
			 L.a("压缩文件失败！");
			 tojson.setFlag(1);
			 tojson.setMsg("文件压缩获取失败");
			 return tojson;
		}
	}
	private static Boolean down(String string, HttpServletResponse response,String stringName) throws IOException {
		response.setCharacterEncoding("utf-8");
		 //response.setContentType("application/octet-stream");
		response.setContentType("multipart/form-data");
		 byte[] bytes = stringName.getBytes("UTF-8"); 
		 stringName= new String(bytes,"ISO-8859-1"); // 各浏览器基本都支持ISO编码
		    response.setHeader("Content-disposition",
		            String.format("attachment; filename=\"%s\"", stringName));
				InputStream inputStream = null;
				OutputStream os = null;
				try {
					 inputStream = new FileInputStream(new File(string));
					 os = response.getOutputStream();
					byte[] b = new byte[2048];
					int length;
					while ((length = inputStream.read(b)) > 0) {
						os.write(b, 0, length);
					}
					os.flush();
					os.close();
					inputStream.close();
					return true;
				} catch (FileNotFoundException e) {
					e.printStackTrace();
					return false;
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}finally {
					if (os != null) {
						os.close();
					}
					if (inputStream != null) {
						inputStream.close();
					}
				}
	}

	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-6-16 下午5:57:04
	 * 方法介绍:   删除指定的文件或者文件夹
	 * 参数说明:   @param file
	 * @return     void
	 */
	public static void deleteFile(File file) {
		if (file.isFile()) {
			file.delete();
			return;
		}
		File[] fileList = file.listFiles();
		for (int i = 0; fileList != null && i < fileList.length; i++) {
			deleteFile(fileList[i]);
		}
		file.delete();
	}
	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-6-16 下午2:24:28
	 * 方法介绍:   拼最后路径 
	 * 参数说明:   @param att
	 * 参数说明:   @param company
	 * 参数说明:   @return
	 * @return     Object
	 */
	private StringBuffer getLessPath(Attachment att, String company) {
		StringBuffer lessPath=new StringBuffer();
		String moduleID=null;
		for(ModuleEnum em:ModuleEnum.values()){
		      if(att.getModule()==em.getIndex()){
		    	 moduleID=em.getName();
		      }
		 }
		lessPath.append(File.separator);
//		lessPath.append("attach");
//		lessPath.append(File.separator);
		lessPath.append(company);
		lessPath.append(File.separator);
		lessPath.append(moduleID);
		lessPath.append(File.separator);
		lessPath.append(att.getYm());
		lessPath.append(File.separator);
		lessPath.append(att.getAttachId());
		lessPath.append(".");
		lessPath.append(att.getAttachName());
		return lessPath;
	}


	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-6-16 下午1:56:54
	 * 方法介绍:   读取路径
	 * 参数说明:   @return
	 * @return     String
	 */
	public StringBuilder getPath(){
		        //读取配置文件
				ResourceBundle rb =  ResourceBundle.getBundle("upload");
				String osName = System.getProperty("os.name");
				StringBuilder sb=new StringBuilder();
				StringBuffer buffer=new StringBuffer();
				if(osName.toLowerCase().startsWith("win")){
					//sb=sb.append(rb.getString("upload.win"));
					//判断路径是否是相对路径，如果是的话，加上运行的路径
					String uploadPath = rb.getString("upload.win");
					if(uploadPath.indexOf(":")==-1){
						//获取运行时的路径
						String basePath = this.getClass().getClassLoader().getResource(".").getPath()+File.pathSeparator;
						//获取截取后的路径
						String str2 = "";
						if(basePath.indexOf("/xoa")!=-1){
							//获取字符串的长度
							int length = basePath.length();
							//返回指定字符在此字符串中第一次出现处的索引
							int index = basePath.indexOf("/xoa");
							//从指定位置开始到指定位置结束截取字符串
							str2=basePath.substring(0,index);
						}
						sb = sb.append(str2 + "/xoa");
					}
					sb.append(uploadPath);
					buffer=buffer.append(rb.getString("upload.win"));
				}else{
					sb=sb.append(rb.getString("upload.linux"));
					buffer=buffer.append(rb.getString("upload.linux"));
				}
				return sb;
	}
	/**
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-6-16 下午1:21:58
	 * 方法介绍:  下载文件生成目录及文件  
	 * 参数说明:   @param filePath
	 * @return     void
	 */
	private static void createDir(String filePath){
		  for(int i=filePath.length()-1;i>=0;i--){
			  if(filePath.charAt(i)=='/' || filePath.charAt(i)=='\\'){
				  File file =new File(filePath.substring(0,i));
				  file.mkdirs();
				  break;
			  }
			  if(filePath.charAt(i)=='.'){
				 String fileName=filePath.substring(filePath.lastIndexOf(File.separator)+1, filePath.length());
				 String  directory=filePath.substring(0,filePath.lastIndexOf(File.separator)+1);
				 //System.out.println("---"+fileName+"-----"+directory);
				  File f = new File(directory,fileName);
			        if(f.exists()) {
			          // 文件已经存在，输出文件的相关信息
			            /*System.out.println(f.getAbsolutePath());
			            System.out.println(f.getName());
			            System.out.println(f.length());*/
			        } else {
			          //  先创建文件所在的目录
			            f.getParentFile().mkdirs();
			            try {
			             // 创建新文件
			                f.createNewFile();
			            } catch (IOException e){
			                //System.out.println("创建新文件时出现了错误。。。");
			                e.printStackTrace();
			            }
			        }
			  }
		  }
	  }
	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-6-16 下午1:23:08
	 * 方法介绍:   将文字信息打印到文件中
	 * 参数说明:   @param contentString
	 * 参数说明:   @param contentPath
	 * @return     void
	 * @throws IOException 
	 */
	public static Boolean writeContent(StringBuilder cententString,String contentPath){
		  File file = new File(contentPath);
          try {
        	 if(file.exists()){
        		 FileOutputStream   aa=new FileOutputStream(file);
			PrintStream ps = new PrintStream(aa);
			ps.println(cententString);
			ps.close();
			aa.close();
        	}
        	 return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	
	}
	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-6-16 下午1:38:34
	 * 方法介绍:   将一个文件复制到另一个文件夹下
	 * 参数说明:   @param from
	 * 参数说明:   @param to
	 * 参数说明:   @return
	 * @return     boolean
	 */
	public static boolean copy(String from, String to) {
		File fromFile = new File(from);
		if (!fromFile.exists() || !fromFile.isFile()) {
			return false;
		}
		File toFileDirectory = new File(to);

		if (!toFileDirectory.exists()) {
			toFileDirectory.mkdirs();
		}

		FileInputStream input = null;
		FileOutputStream output = null;
		byte b[] = new byte[1024];
		int i = 0;
		try {
			if(fromFile.exists()){
			   input = new FileInputStream(fromFile);
		     }else{
		    	 L.a("该文件不存在或者路径不对！");
		     }
			output = new FileOutputStream(new File(to + "/"
					+ fromFile.getName()));
			while ((i = input.read(b)) != -1) {
				output.write(b, 0, i);
			}
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-6-16 下午6:19:09
	 * 方法介绍:   将指定的文件夹进行压缩到相应的目录下
	 * 参数说明:   @param sourceDir
	 * 参数说明:   @param zipFilePath
	 * 参数说明:   @return
	 * 参数说明:   @throws IOException
	 * @return     File
	 */
	 public File doZip(String sourceDir, String zipFilePath) 
			  throws IOException {
			   File file = new File(sourceDir);
			   File zipFile = new File(zipFilePath);
			   ZipOutputStream zos = null;
			   try {
			    // 创建写出流操作
			    OutputStream os = new FileOutputStream(zipFile);
			    BufferedOutputStream bos = new BufferedOutputStream(os);
			    zos = new ZipOutputStream(bos);
			    
			    String basePath = null;
			    
			    // 获取目录
			    if(file.isDirectory()) {
			     basePath = file.getPath();
			    }else {
			     basePath = file.getParent();
			    }
			    
			    zipFile(file, basePath, zos);
			   }finally {
			    if(zos != null) {
			     zos.closeEntry();
			     zos.close();
			    }
			   }
			   
			   return zipFile;
			  }

	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-6-20 下午8:00:30
	 * 方法介绍:   压缩文件
	 * 参数说明:   @param source
	 * 参数说明:   @param basePath
	 * 参数说明:   @param zos
	 * 参数说明:   @throws IOException
	 * @return     void
	 */
	 private void zipFile(File source, String basePath, ZipOutputStream zos) 
			  throws IOException {
			   File[] files = null;
			   if (source.isDirectory()) {
			    files = source.listFiles();
			   } else {
			    files = new File[1];
			    files[0] = source;
			   }
			   
			   InputStream is = null;
			   String pathName;
			   byte[] buf = new byte[1024];
			   int length = 0;
			   try{
			    for(File file : files) {
			     if(file.isDirectory()) {
			      pathName = file.getPath().substring(basePath.length() + 1) + "/";
			      zos.putNextEntry(new ZipEntry(pathName));
			      zipFile(file, basePath, zos);
			     }else {
			      pathName = file.getPath().substring(basePath.length() + 1);
			      is = new FileInputStream(file);
			      BufferedInputStream bis = new BufferedInputStream(is);
			      zos.putNextEntry(new ZipEntry(pathName));
			      while ((length = bis.read(buf)) > 0) {
			       zos.write(buf, 0, length);
			      }
			     }
			    }
			   }finally {
			    if(is != null) {
			     is.close();
			    }
			   }
			  }

	 public static String getString(Object str){
			if(str==null){
				return "";
			}
			return String.valueOf(str);
		}
	 public static Integer getInteger(Object str){
			if(str==null||"".equals(str)){
				return 0;
			}
			try {
				return  Integer.parseInt(String.valueOf(str));
			} catch (Exception e) {
				e.printStackTrace();
				return 0;
			}
		}

	 public static int getInteger(Object str,int def){
			String s = getString(str);
			int dot = s.indexOf('.');
			if(dot!=-1){
				s = s.substring(0, dot);
			}
			if(!"".equals(s)){
				try{
					return Integer.parseInt(s);
				}catch(Exception e){
					e.printStackTrace();
					return def;
				}
			}
			return def;
		}

	 /**
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-7-5 下午3:13:53
	 * 方法介绍:   全局搜索
	 * 参数说明:   @param paramMap
	 * 参数说明:   @return
	 * @return     ToJson<?>   
	 */
	@SuppressWarnings({ "static-access", "unchecked" })
	@Override
	public ToJson serachAll(Map<String, String> paramMap,HttpServletRequest request) {
		ToJson tojson=new ToJson();
		Integer serachType=this.getInteger(paramMap.get("serachType"));
		String subject=this.getString(paramMap.get("subject"));
		String keyword1=this.getString(paramMap.get("keyword1"));
		String keyword2=this.getString(paramMap.get("keyword2"));
		String keyword3=this.getString(paramMap.get("keyword3"));
		String content=this.getString(paramMap.get("content"));
		String begainTime=this.getString(paramMap.get("begainTime"));
		String endTime=this.getString(paramMap.get("endTime"));
		String creater=this.getString(paramMap.get("creater"));
		String attScript=this.getString(paramMap.get("attScript"));
		String attContain=this.getString(paramMap.get("attContain"));
		String attName=this.getString(paramMap.get("attName"));
		String sort_no=this.getString(paramMap.get("sort_no"));
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("subject", subject);
		map.put("keyword1", keyword1);
		map.put("keyword2", keyword2);
		map.put("keyword3", keyword3);
		map.put("content", content);
		map.put("begainTime", begainTime);
		map.put("endTime", endTime);
		map.put("creater", creater);
		map.put("attScript", attScript);
		map.put("attContain", attContain);
		map.put("attName", attName);
		map.put("sort_no", sort_no);
		switch (serachType) {
		case 1:
			List<FileContentModel> personList=serachPerson(request,map);
			tojson.setObj(personList);
			tojson.setFlag(0);
			break;
        case 2:
        	List<FileContentModel> commonList=serachCommon(request,map);
        	tojson.setObj(commonList);
			tojson.setFlag(0);
			break;
		default:
			tojson.setFlag(1);
			tojson.setMsg("参数不对");
			break;
		}
		
		return tojson;
	}
	
	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-5-8 下午3:45:58
	 * 方法介绍:   递归个人文件柜
	 * 参数说明:   @param file
	 * 参数说明:   @return
	 * @return     List<FileSortModel>
	 */
	public List<FileSortModel> getchildTreePerson(FileSortModel file) {
		// 传值查询子节点数据
		List<FileSortModel> parentList = new ArrayList<FileSortModel>();
		int tempNo = file.getSortId();
		List<FileSortModel> childrenList = new ArrayList<FileSortModel>();
		childrenList = fileSortService.getSortChrildren(tempNo);
		if(childrenList.size()>0){
		for (FileSortModel fs : childrenList){
			parentList.addAll(getchildTreePerson(fs));
		}
		parentList.addAll(childrenList);
		}
		return parentList;
	}
	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-7-5 下午8:15:06
	 * 方法介绍:   个人文件柜全局搜索
	 * 参数说明:   @param request
	 * 参数说明:   @param map
	 * 参数说明:   @return
	 * @return     List<FileContentModel>
	 */
	public List<FileContentModel> serachPerson(HttpServletRequest request,Map<String, Object> map){
		  HttpSession session=request.getSession();
			String userId=session.getAttribute("userId").toString();
			String userPriv=session.getAttribute("userPriv").toString();
			String deptId=session.getAttribute("deptId").toString();
			Map<String,Object> maps=new Hashtable<String, Object>();
			maps.put("userId", userId);
			maps.put("userPriv", userPriv);
			maps.put("deptId", deptId);
		     List<FileSortModel> rootTree = new LinkedList<FileSortModel>();
		     FileSortModel fs=new FileSortModel();
				fs.setUserId(userId);
				fs.setSortName("根文件夹");
				fs.setSortType("4");
				fs.setSortParent(-1);
				fs.setSortId(0);
				
		     FileSortModel fsm=new FileSortModel();
			fsm.setUserId(userId);
			fsm.setSortType("4");
			fsm.setSortParent(0);
			List<FileSortModel> fList=fileSortService.getFileSortList(fsm);
			if(fList==null){
				fList =new ArrayList<FileSortModel>();
			 }
			rootTree.addAll(fList);// 根节点
			
			List<FileSortModel> childTree = new LinkedList<FileSortModel>();
			for(FileSortModel f:rootTree){
				if(fsm.getSortParent()!=-1){
				childTree.addAll(getchildTreePerson(f));
				}
			}
			rootTree.addAll(childTree);
			rootTree.add(fs);
			StringBuffer sortid=new StringBuffer("");
			for(FileSortModel fm:rootTree){
				sortid.append(fm.getSortId());
				sortid.append(",");
			}
			map.put("sortid",sortid.substring(0, sortid.toString().length()-1));
			map.put("userId", userId);
			List<FileContentModel> list=file_ContentMapper.searchPerson(map);
			for(FileContentModel fc:list){
				String temp=fc.getSendTime().substring(0, 19);
				fc.setSendTime(temp);
				StringBuffer path=new StringBuffer("");
				getfolderPath(fc.getSortId(),path,null,null);
				fc.setFilePath(path.toString());
				List<Attachment> attachmentList=new ArrayList<Attachment>();
				if(fc.getAttachmentName()!=null&&!"".equals(fc.getAttachmentName())){
					attachmentList=GetAttachmentListUtil.returnAttachment(fc.getAttachmentName(),fc.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"),GetAttachmentListUtil.MODULE_FILE_FOLDER);
					}
				fc.setAttachmentList(attachmentList);
			}
		return list;
		
	}
	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-4-18 下午4:15:03
	 * 方法介绍:   根据权限递归循环获取文件夹对象
	 * 参数说明:   @param file
	 * 参数说明:   @return
	 * @return     List<FileSortModel>
	 */
	public List<FileSortModel> getchildTrees(FileSortModel file,Map<String,Object> map) {
		// 传值查询子节点数据
		List<FileSortModel> parentList = new ArrayList<FileSortModel>();
		int tempNo = file.getSortId();
		List<FileSortModel> childrenList = new ArrayList<FileSortModel>();
		childrenList = fileSortService.getSortChrildren(tempNo);
		if(childrenList.size()>0){
		for (FileSortModel fs : childrenList){
			parentList.addAll(getchildTrees(fs,map));
		}
		parentList.addAll(childrenList);
		}
		return parentList;
	}
	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-7-5 下午8:15:37
	 * 方法介绍:   公共文件柜全局搜索
	 * 参数说明:   @param request
	 * 参数说明:   @param map
	 * 参数说明:   @return
	 * @return     List<FileContentModel>
	 */
	public List<FileContentModel> serachCommon(HttpServletRequest request,Map<String, Object> map){
		 HttpSession session=request.getSession();
			String userId=session.getAttribute("userId").toString();
			String userPriv=session.getAttribute("userPriv").toString();
			String deptId=session.getAttribute("deptId").toString();
			Map<String,Object> maps=new Hashtable<String, Object>();
			maps.put("userId", userId);
			maps.put("userPriv", userPriv);
			maps.put("deptId", deptId);
		    //采用 LinkedList 双向列表实现类 操作 在链表中操作对象集合效率高
			List<FileSortModel> rootTree=new LinkedList<FileSortModel>();
			Map<String,Object> rootMap=new HashMap<String,Object>();
			int sortid=0;
			rootMap.put("sortid",sortid);
			rootMap.put("sortType","5");
			rootTree = fileSortService.getRootTree(rootMap);// 根节点
			//利用迭代器删除集合中元素
			List<FileSortModel> childTree = new LinkedList<FileSortModel>();

			for(FileSortModel fsm:rootTree){
				childTree.addAll(getchildTrees(fsm,map));
			}
			rootTree.addAll(childTree);
			Iterator<FileSortModel> iteratorChr=rootTree.iterator();
			while(iteratorChr.hasNext()){
						FileSortModel fsm=iteratorChr.next();
						//将权限字符串传到checkAll 返回为true时 有权限 为false时无权限
						if(!CheckTree.checkAll(fsm.getUserId()==null?"":fsm.getUserId(),maps)){
							iteratorChr.remove();
				        }
			}
			StringBuffer sortids=new StringBuffer("");
			for(FileSortModel fm:rootTree){
				sortids.append(fm.getSortId());
				sortids.append(",");
			}
			map.put("sortid", sortids.toString().substring(0, sortids.toString().length()-1));
			List<FileContentModel> list=file_ContentMapper.serachCommon(map); 
			for(FileContentModel fc:list){
				String temp=fc.getSendTime().substring(0, 19);
				fc.setSendTime(temp);
				StringBuffer path=new StringBuffer("");
				//权限表示1为有权限 0为无权限
				Map<String ,Object> mapPriv=new HashMap<String, Object>();
				//递归路径信息
				getfolderPath(fc.getSortId(),path,mapPriv,maps);
				fc.setMapPriv(mapPriv);
				fc.setFilePath(path.toString());
				List<Attachment> attachmentList=new ArrayList<Attachment>();
				if(fc.getAttachmentName()!=null&&!"".equals(fc.getAttachmentName())){
					attachmentList=GetAttachmentListUtil.returnAttachment(fc.getAttachmentName(),fc.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"),GetAttachmentListUtil.MODULE_FILE_FOLDER);
					}
				fc.setAttachmentList(attachmentList);
			}
		 return list;
	}
	
	public  void  getfolderPath(Integer integer,StringBuffer path,Map<String ,Object> mapPriv,Map<String,Object> maps){
		if(integer!=0&&integer!=null){
		  FileSortModel pathFolder=fileSortMapper.getfolderPath(integer);
		  if(pathFolder!=null){
            if(mapPriv!=null&&maps!=null){
            	//访问权限
            	mapPriv.put("USER_ID", CheckTree.checkAll(pathFolder.getUserId(), maps)==true?1:0);
        		//有新建权限
        		mapPriv.put("NEW_USER", CheckTree.checkAll(pathFolder.getNewUser(), maps)==true?1:0);
        		//有编辑权限
        		mapPriv.put("MANAGE_USER",  CheckTree.checkAll(pathFolder.getManagerUser(), maps)==true?1:0);
        		//有删除权限
        	    mapPriv.put("DEL_USER",  CheckTree.checkAll(pathFolder.getDelUser(), maps)==true?1:0);
        		//有下载/打印权限
        		mapPriv.put("DOWN_USER",  CheckTree.checkAll(pathFolder.getDownUser(), maps)==true?1:0);
        		//有签阅权限
        		mapPriv.put("SIGN_USER", CheckTree.checkAll(pathFolder.getSignUser(), maps)==true?1:0);
        		//评论/打分权限
        		mapPriv.put("REVIEW",  CheckTree.checkAll(pathFolder.getReview(), maps)==true?1:0);
        		//所有者
        		mapPriv.put("OWNER",  CheckTree.checkAll(pathFolder.getOwner(), maps)==true?1:0);
            }
		  path.insert(0, pathFolder.getSortName());
		  path.insert(0, "/");
		  if(pathFolder.getSortParent()!=0){
		  getfolderPath(pathFolder.getSortParent(),path,null,null);
		  }
		   }
		}else{
			path.insert(0, "根文件夹");
			path.insert(0, "/");
		}
	}
//	public  void  getfolderPathComm(Integer integer,StringBuffer path){
//		  FileSortModel pathFolder=fileSortMapper.getfolderPath(integer);
//		  if(pathFolder!=null){
//		  path.insert(0, pathFolder.getSortName());
//		  path.insert(0, "/");
//		  i
//		  getfolderPath(pathFolder.getSortParent(),path);
//		  }
//	}

	@Override
	public ToJson signConState(Map<String, String> paramMap,HttpServletRequest request) {
		ToJson tojson=new ToJson();
		String contentId=this.getString(paramMap.get("contentId"));
		FileContentModel fileContentModel=file_ContentMapper.getFileConByContentId(contentId);
		if(fileContentModel==null){
			tojson.setFlag(1);
			tojson.setMsg("没有这个文件");
			return tojson;
		}
		FileSortModel fs=new FileSortModel();
		fs.setSortId(fileContentModel.getSortId());
		FileSortModel tempFile=fileSortMapper.getOne(fs);
		if(tempFile==null){
			tojson.setFlag(1);
			tojson.setMsg("没有这个文夹");
			return tojson;
		}
		List<Users> unReadList = new ArrayList<Users>();
		List<Users> readList = new ArrayList<Users>();
 		String signUser=tempFile.getUserId();
 	    Map<String,Object>  mapUser=checkUser(signUser);
 		if(mapUser!=null){
 			if("AllDeptId".equals(mapUser.get("dept_id"))){
 				unReadList=usersService.selectFileUserSignerAll();
 			}else{
 				unReadList=usersService.selectFileUserSigner(mapUser);}
 		}
 		if(unReadList.size()>0){
 		Iterator<Users> userIt=unReadList.iterator();
 		while (userIt.hasNext()) {
 		Users type = userIt.next();
 		String[]	readers=fileContentModel.getReaders().split(",");
 		List<String> List=Arrays.asList(readers);
 		 if(List.contains(type.getUserId())){
 			readList.add(type);
 			userIt.remove();
 			continue;
 		    }
		  }
 		}
		List<Department> resultList = new ArrayList<Department>();
		List<Department> departmentList = departmentMapper.getDatagrid();
		// List<Department>  departmentList1=new ArrayList<>();
		for (Department department : departmentList) {
			StringBuffer stringBuffer = new StringBuffer();
			for (Users users : unReadList) {
				Integer depId = users.getDeptId();
				if (department.getDeptId().equals(depId)) {
					stringBuffer.append(users.getUserName());
					stringBuffer.append(",");
				}
			}
			department.setUnread(stringBuffer.toString());
			StringBuffer stringBuffer1 = new StringBuffer();
			for (Users users : readList) {
				Integer depId = users.getDeptId();
				if (department.getDeptId().equals(depId)) {
					stringBuffer1.append(users.getUserName());
					stringBuffer1.append(",");
				}
			}
			department.setRead(stringBuffer1.toString());
  }
		tojson.setObj(departmentList);
		tojson.setObject(fileContentModel);
		tojson.setFlag(0);
		tojson.setMsg(unReadList.size()+","+readList.size());
		return tojson;
	}

	@Override
	public List<FileContentModel> selectFileSortList(String sortList) {
		return file_ContentMapper.selectFileSortList(sortList);
	}

	@Override
	public ToJson<FileContentModel> queryFileContent(String fileTitle) {
		ToJson<FileContentModel> tojson = new ToJson();
		try{
			List<FileContentModel> list = file_ContentMapper.queryFileContent(fileTitle);
			if(list!=null){
				tojson.setObj(list);
				tojson.setMsg("数据获取成功");
			}
			tojson.setFlag(0);

		}catch (Exception e){
			e.printStackTrace();
			tojson.setMsg(e.getMessage());
			tojson.setFlag(1);
		}
		return tojson;
	}

	public static Map<String,Object> checkUser(String checkString){
		Map<String,Object> map=new HashMap<String, Object>();
		//"|"转义字符串  所以必须用\\进行转义 因为 而且取出数组长度不确定
	   String[] checkStrings=checkString.split("\\|");
	   if(checkStrings.length==0){
		   return null;
	   }
	     //数组长度为1时 说明此时角色和用户Id权限为空
	   if(checkStrings.length==1&&!"".equals(checkStrings[0])){
		   String[]  checkDept=checkStrings[0].split(",");
			   if("ALL_DEPT".equalsIgnoreCase(checkStrings[0])){
				   map.put("dept_id", "AllDeptId");
			   }
			   else{
				   if("".equals(checkStrings[0])){
				   map.put("dept_id","");
				   }else{
					   map.put("dept_id",checkStrings[0].substring(0, checkStrings[0].length()-1));
				   }
			   }
	   }
	     //数组长度为2时 说明此时用户Id权限为空
	   if(checkStrings.length==2){
		   String[]  checkDept=checkStrings[0].split(",");
			   if("ALL_DEPT".equalsIgnoreCase(checkStrings[0])){
				   map.put("dept_id", "AllDeptId");
			   }
			   else{
				   if("".equals(checkStrings[0])){
					   map.put("dept_id","");
					   }else{
						   map.put("dept_id",checkStrings[0].substring(0, checkStrings[0].length()-1));
					   }
			   }
		   //String[]  checkUserPriv=checkStrings[1].split(",");
			   if("".equals(checkStrings[1])){
				   map.put("user_Priv", checkStrings[1]);
				   }else{
					   map.put("user_Priv", checkStrings[1].substring(0, checkStrings[1].length()-1));
				   }
	   }
	     //数组长度为3时 说明此时部门、角色和用户Id权限都不为空
	   if(checkStrings.length==3){
		   String[]  checkDept=checkStrings[0].split(",");
		   if("ALL_DEPT".equalsIgnoreCase(checkStrings[0])){
			   map.put("dept_id", "AllDeptId");
		   }
		   else{
			   if("".equals(checkStrings[0])){
				   map.put("dept_id","");
				   }else{
					   map.put("dept_id",checkStrings[0].substring(0, checkStrings[0].length()-1));
				   }
		   }
	  // String[]  checkUserPriv=checkStrings[1].split(",");
		   if("".equals(checkStrings[1])){
			   map.put("user_Priv", checkStrings[1]);
			   }else{
				   map.put("user_Priv", checkStrings[1].substring(0, checkStrings[1].length()-1));
			   }
		   String[]  checkUserId=checkStrings[2].split(",");
		   StringBuffer sbUserID=new StringBuffer("");
		   for(int i=0;i<checkUserId.length;i++){
			   sbUserID.append("'");
			   sbUserID.append(checkUserId[i]);
			   sbUserID.append("'");
			   if(i<checkUserId.length-1){
				   sbUserID.append(",");
			   }
		   }
		   map.put("user_id", sbUserID.toString());
	   }
	return map;
	}
	List<TreeNode> treeFile(Integer sortid, HttpSession session) {
		//Session 获取用户信息
		String userId = session.getAttribute("userId").toString();
		String userPriv = session.getAttribute("userPriv").toString();
		String deptId = session.getAttribute("deptId").toString();
		Map<String, Object> map = new Hashtable<String, Object>();
		map.put("userId", userId);
		map.put("userPriv", userPriv);
		map.put("deptId", deptId);
		//采用 LinkedList 双向列表实现类 操作 在链表中操作对象集合效率高
		List<FileSortModel> rootTree = new LinkedList<FileSortModel>();
		Map<String, Object> rootMap = new HashMap<String, Object>();
		if (sortid == null) sortid = 0;
		rootMap.put("sortid", sortid);
		rootMap.put("sortType", "5");
		rootTree = fileSortService.getRootTree(rootMap);// 根节点
		//利用迭代器删除集合中元素
		List<FileSortModel> childTree = new LinkedList<FileSortModel>();

		for (FileSortModel fsm : rootTree) {
			childTree.addAll(getchildTrees(fsm, map));
		}
		// 构造方法传值
		FileCommSortTreeUtil util = new FileCommSortTreeUtil(rootTree, childTree, map);
		return util.getTreeNode();
	}

	List<FileSortModel> getfilesDeleteList(FileSortModel file) {
		// 传值查询子节点数据
		List<FileSortModel> parentList = new ArrayList<FileSortModel>();
		Integer tempNo = file.getSortId();
		List<FileSortModel> childrenList = new ArrayList<FileSortModel>();
		childrenList = fileSortService.getSortChrildren(tempNo);
		if (childrenList.size() > 0) {
			for (FileSortModel fs : childrenList) {
				parentList.addAll(getfilesDeleteList(fs));
			}
			parentList.addAll(childrenList);
		}
		return parentList;
	}
}
